package com.example.firstdemo.ui.screens.pages.addProblem.addProblem

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.addDescription.navigateToAddDescription
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectCarriage.navigateToSelectCarriage
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectPosition.navigateToSelectPosition
import com.example.firstdemo.ui.screens.pages.addProblem.addProblem.selectProblem.navigateToSelectProblem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable


@Serializable
object AddProblem


fun NavGraphBuilder.addProblemDestination(
    padding: PaddingValues = PaddingValues(0.dp),
    navController: NavController
) {
    composable<AddProblem> {
        val viewModel: AddProblemViewModel = viewModel()
        val uiState = viewModel.uiState.collectAsState().value
        AddProblemScreen(
            padding = padding,
            uiState = uiState,
            onBack = {
                CoroutineScope(Dispatchers.Main).launch {
                    navController.popBackStack()
                    delay(500)
                    viewModel.resetUIState()
                }
            },
            onSelectCarriage = navController::navigateToSelectCarriage,
            onSelectPosition = navController::navigateToSelectPosition,
            onSelectProblem = navController::navigateToSelectProblem,
            onAddDescription = navController::navigateToAddDescription,
            onSave = { path ->
                CoroutineScope(Dispatchers.IO).launch {
                    viewModel.save(path)
                    withContext(Dispatchers.Main) {
                        navController.popBackStack()
                    }
                }
            }
        )
    }
}

fun NavController.navigateToAddProblem(navOptions: NavOptions? = null) {
    navigate(AddProblem, navOptions)
}